/*
 *
 *      Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: lengleng (wangiegie@gmail.com)
 *
 */

package com.pig4cloud.pig.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.admin.api.dto.DeptTree;
import com.pig4cloud.pig.admin.api.entity.SysDept;
import com.pig4cloud.pig.admin.api.entity.SysDeptGroup;
import com.pig4cloud.pig.admin.api.entity.SysDeptRelation;
import com.pig4cloud.pig.admin.api.entity.SysUserTenant;
import com.pig4cloud.pig.admin.api.vo.TreeUtil;
import com.pig4cloud.pig.admin.mapper.SysDeptMapper;
import com.pig4cloud.pig.admin.service.SysDeptGroupService;
import com.pig4cloud.pig.admin.service.SysDeptRelationService;
import com.pig4cloud.pig.admin.service.SysDeptService;
import com.pig4cloud.pig.admin.service.SysUserTenantService;
import com.pig4cloud.pig.common.core.util.R;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author lengleng
 * @since 2018-01-20
 */
@Service
@AllArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
	private final SysDeptRelationService sysDeptRelationService;
	private final SysDeptGroupService sysDeptGroupService;
	private final SysUserTenantService sysUserTenantService;

	/**
	 * 添加信息部门
	 *
	 * @param dept 部门
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean saveDept(SysDept dept) throws Exception {
		SysDept sysDept = new SysDept();
		BeanUtils.copyProperties(dept, sysDept);
		this.save(sysDept);
		sysDeptRelationService.insertDeptRelation(sysDept);
		if (CollectionUtils.isNotEmpty(dept.getGroupList())) {
			dept.getGroupList().stream().filter(v -> !Objects.isNull(v)).forEach(v -> {
				v.setDeptId(sysDept.getDeptId());
			});
			sysDeptGroupService.saveOrUpDateSysDeptGroups(dept.getGroupList());
		}
		return Boolean.TRUE;
	}


	/**
	 * 删除部门
	 *
	 * @param id 部门 ID
	 * @return 成功、失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean removeDeptById(Integer id) {
		//级联删除部门
		List<Integer> idList = sysDeptRelationService
				.list(Wrappers.<SysDeptRelation>query().lambda()
						.eq(SysDeptRelation::getAncestor, id))
				.stream()
				.map(SysDeptRelation::getDescendant)
				.collect(Collectors.toList());

		if (CollUtil.isNotEmpty(idList)) {
			this.removeByIds(idList);
		}

		//删除部门级联关系
		sysDeptRelationService.deleteAllDeptRealtion(id);
		sysDeptGroupService.delSysDeptGroupByDeptId(id);
		return Boolean.TRUE;
	}

	/**
	 * 删除部门
	 *
	 * @param id 部门 ID
	 * @return 成功、失败
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public R removeDeptById1(Integer id) {

		// 如果存在子部门则不允许删除
		int childrenCount = this.count(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId, id));
		if (childrenCount > 0) {
			return R.failed("请先删除关联的子部门，然后再删除当前部门");
		}

		// 如果存在组别则不允许删除
		int deptGroupCount = sysDeptGroupService.count(Wrappers.<SysDeptGroup>lambdaQuery().eq(SysDeptGroup::getDeptId, id));
		if (deptGroupCount > 0) {
			return R.failed("请先删除关联的组别，然后再删除当前部门");
		}

		// 如果已关联到用户则不允许删除
		int userCount = sysUserTenantService.count(Wrappers.<SysUserTenant>lambdaQuery().eq(SysUserTenant::getDeptId, id));
		if (userCount > 0) {
			return R.failed("请先删除与用户的关联关系，然后再删除当前部门");
		}

		// 删除部门信息
		this.removeById(id);

		// 删除部门级联关系
		sysDeptRelationService.deleteAllDeptRealtion(id);
		sysDeptGroupService.delSysDeptGroupByDeptId(id);
		return R.ok();
	}

	/**
	 * 更新部门
	 *
	 * @param sysDept 部门信息
	 * @return 成功、失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updateDeptById(SysDept sysDept) throws Exception {
		//更新部门状态
		this.updateById(sysDept);
		//更新部门关系
		SysDeptRelation relation = new SysDeptRelation();
		relation.setAncestor(sysDept.getParentId());
		relation.setDescendant(sysDept.getDeptId());
		sysDeptRelationService.updateDeptRealtion(relation);
		if (CollectionUtils.isNotEmpty(sysDept.getGroupList())) {
			sysDept.getGroupList().stream().forEach(v -> v.setDeptId(sysDept.getDeptId()));
			sysDeptGroupService.saveOrUpDateSysDeptGroups(sysDept.getGroupList());
		}
		return Boolean.TRUE;
	}

	/**
	 * 查询全部部门树
	 *
	 * @return 树
	 */
	@Override
	public List<DeptTree> selectTree() {
		return getDeptTree(this.list(Wrappers.emptyWrapper()));
	}


	/**
	 * 构建部门树
	 *
	 * @param depts 部门
	 * @return
	 */
	private List<DeptTree> getDeptTree(List<SysDept> depts) {
		Integer root = 0;
		if (CollectionUtils.isNotEmpty(depts)) {
			SysDept sysDept = depts.stream().min(Comparator.
					comparingDouble((dept) -> dept.getParentId())).get();
			root = sysDept.getParentId();
		}
		List<DeptTree> treeList = depts.stream()
				.filter(dept -> !dept.getDeptId().equals(dept.getParentId()))
				.sorted(Comparator.comparingInt(SysDept::getSort))
				.map(dept -> {
					DeptTree node = new DeptTree();
					node.setId(dept.getDeptId());
					node.setParentId(dept.getParentId());
					node.setName(dept.getName());
					return node;
				}).collect(Collectors.toList());

		return TreeUtil.build(treeList, root);
	}

	/**
	 * 查询当前可查询的部门列表树形菜单
	 *
	 * @param deptName 部门名称，模糊查询
	 * @param deptArr  多个部门用逗号分隔
	 * @return
	 */
	@Override
	public List<DeptTree> getUserDeptTree(String deptName, String deptArr) {
		log.error("deptName: "+deptName+"____deptArr: "+deptArr);
		List<SysDept> sysDeptList = getUserDeptList(deptName, deptArr);
		List<DeptTree> deptTreeList = getDeptTree(sysDeptList);
		return deptTreeList;
	}

	/**
	 * 查询当前可查询的部门列表
	 *
	 * @param deptName
	 * @param deptArr
	 * @return
	 */
	@Override
	public List<SysDept> getUserDeptList(String deptName, String deptArr) {
		if (StringUtils.isEmpty(deptArr)) {
			return new ArrayList<>();
		}
		List<String> deptIdArr = Arrays.asList(deptArr.split(","));
		List<SysDept> sysDeptList = baseMapper.selectList(Wrappers.<SysDept>query().lambda().like(SysDept::getName, deptName).in(SysDept::getDeptId, deptIdArr));
		return sysDeptList;
	}
}
